package com.ysjy.course.service.impl;

import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.constants.PromptMessage;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.ClassInfo;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.utils.DateUtil;
import com.wkbb.common.utils.RandomUtil;
import com.wkbb.sports.mapper.BasicMapper;
import com.ysjy.course.mapper.*;
import com.ysjy.course.model.*;
import com.ysjy.course.service.CourseClassService;
import com.ysjy.course.service.SignUpUserService;
import com.ysjy.course.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class SignUpUserServiceImpl extends BaseServiceImpl<SignUpUser> implements SignUpUserService {

    @Autowired
    private SignUpUserMapper signUpUserMapper;
    @Autowired
    private BasicMapper basicMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private TrusteeshipMapper trusteeshipMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CourseClassService courseClassService;

    @Autowired
    public void setMapper(SignUpUserMapper mapper) {
        super.setMapper(mapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Boolean> putSignUpUser(SignUpUser data) throws Exception{
        data.setPayType(0);
        //生成订单
        YsOrder ysOrder = new YsOrder();
        //订单类型 1课程 2托管
        if (data.getSignUpType() == 1){
            OrgCourse orgCourse = courseMapper.getOrgCourseByUniqueId(data.getGoodNumber(), data.getStudentId());
            if (orgCourse == null){
                return ResultDTO.errorResult(PromptMessage.COURSE_IS_NULL);
            }
            orgCourse.initSignUpStatus();
            if (orgCourse.getSignUpStatus() == 3){
                return ResultDTO.errorResult(PromptMessage.HAVE_SIGN_UP);
            }
            data.setTitle(orgCourse.getTitle());
            ysOrder.setLogo(orgCourse.getLogo());
            ysOrder.setOriginalAmount(orgCourse.getAmount());
        }else{
            YsTrusteeship trusteeship = trusteeshipMapper.getTrusteeshipByUniqueId(data.getGoodNumber(),data.getStudentId());
            if (trusteeship == null){
                return ResultDTO.errorResult(PromptMessage.TRUSTEESHIP_IS_NULL);
            }
            trusteeship.initSignUpStatus();
            if (trusteeship.getSignUpStatus() == 3){
                return ResultDTO.errorResult(PromptMessage.HAVE_SIGN_UP);
            }
            data.setTitle(trusteeship.getTitle());
            ysOrder.setLogo(trusteeship.getLogo());
            ysOrder.setOriginalAmount(trusteeship.getAmount());
        }
        StudentInfoDto studentInfoDto = basicMapper.getStudentInfoByStudentId(data.getStudentId());
        if (studentInfoDto != null){
            data.setStuName(studentInfoDto.getName());
            data.setStuGradeName(studentInfoDto.getGradeName());
            data.setStuClassName(studentInfoDto.getClassName());
            data.setOrgId(studentInfoDto.getOrgId());
            data.setOrgName(studentInfoDto.getOrgName());

            ysOrder.setStuName(studentInfoDto.getName());
            ysOrder.setStuGradeName(studentInfoDto.getGradeName());
            ysOrder.setStuClassName(studentInfoDto.getClassName());
            ysOrder.setOrgId(studentInfoDto.getOrgId());
            ysOrder.setOrgName(studentInfoDto.getOrgName());
        }
        data.setOrderNumber(DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
        data.setUpdateTime(new Date());
//        log.info(JsonUtil.objectToJson(data));
        signUpUserMapper.insert(data);

        //自动进班
        courseClassService.joinClassBySignUpUser(data);

        ysOrder.setTitle(data.getTitle());
        ysOrder.setStudentId(data.getStudentId());
        ysOrder.setAmount(data.getAmount());
        ysOrder.setOrderNumber(data.getOrderNumber());
        ysOrder.setPayStatus(1);
        ysOrder.setPayTime(new Date());
        ysOrder.setOrderType(data.getSignUpType());
        ysOrder.setPayType(0);
        ysOrder.setUpdateTime(new Date());
        ysOrder.setGoodNumber(data.getGoodNumber());
        orderMapper.insert(ysOrder);
        return ResultDTO.successResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDTO<Boolean> refund(Long id,Integer refundAmount,String refundWhy, UserDto userDto) throws Exception{
        //报名表刷新
        SignUpUser signUpUser = signUpUserMapper.getByPrimaryKey(id);
        if (signUpUser == null){
            return ResultDTO.errorResult("不存在的报名ID");
        }
        if (signUpUser.getRefundStatus() == 1){
            return ResultDTO.errorResult("已退款订单，不能进行该操作");
        }

        ResultDTO<Boolean> resultDTO;
        if (signUpUser.getOrderNumber() != null){
            YsOrder order = orderMapper.getOrderByNumber(signUpUser.getOrderNumber());
            if (order == null){
                return ResultDTO.errorResult("不存在的订单");
            }
            order.setRefundNumber("rf"+DateUtil.getTodayyyyMMddHHmm() + RandomUtil.generateNumber(4));
            order.setRefundAmount(refundAmount);
            resultDTO = WeChatPayUtil.refund(order);
            if (resultDTO.isSuccess()){
                order.setRefundStatus(1);
                order.setRefundTime(new Date());
                order.setRefundWhy(refundWhy);
                order.setApplyRefundTime(new Date());
                order.setAuditUserId(userDto.getId());
                order.setAuditUserName(userDto.getName());
                orderMapper.update(order);

                //课程包统一退款
                signUpUser.setRefundStatus(1);
                signUpUser.setRefundTime(new Date());
                signUpUserMapper.updateRefundStatus(signUpUser);
            }
        }else{
            signUpUser.setRefundStatus(1);
            signUpUser.setRefundTime(new Date());
            signUpUserMapper.update(signUpUser);
            resultDTO = new ResultDTO<>();
        }
        return resultDTO;
    }

}
